const express = require('express');
const router = express.Router();
const mysql = require('mysql');
const constant = require('../data/constant');
const auth = require('../middleware/auth');
const bcrypt = require('bcrypt');


// 获取个人信息的接口
router.get('/personal_info',auth, (req, res) => {
    var Pool = mysql.createPool({
        'host':constant.DB_HOST_NAME,
        'user':constant.DB_USER,
        'password':constant.DB_PWD,
        'database':constant.DB_NAME,
        'multipleStatements': true // 支持执行多条 sql 语句
    });
    Pool.getConnection( (err,connection) => {
        if(err){
            console.log(err);
            res.send({
                'res':{
                    'ok': 0,
                    'msg':'数据库连接失败'
                }
            });
        }else{
            // 构造sql语句
            let  sql = "SELECT * FROM user WHERE uid = ?;"
            let  sqlParams = [
                req.query.uid,
            ];
            connection.query(sql,sqlParams,async (err,data) => {
                if(err){
                    console.log(err);
                    res.statusCode = 500;
                    res.send({
                        'res':{
                            'ok': 0,
                            'msg':'数据库连接失败'
                        }
                    });
                }else{
                    let res_data = JSON.stringify(data);//把data对象转为字符串，去掉RowDataPacket
                    res_data = JSON.parse(res_data);//把results字符串转为json对象
                    // console.log(res_data);
                    if(res_data.length >= 1){
                        let type = '';
                        switch(res_data[0].role){
                            case 0:type = '学生';break;
                            case 1:type = '教师';break;
                            case 2:type = '企业用户';break;
                            case 3:type = '库管理员';break;
                            case 4:type = '系统管理员';break;
                        }
                        // 处理数据
                        let result = {
                            'username':res_data[0].username,
                            'uid':res_data[0].uid,
                            'type':type
                            
                        };
                        res.send({
                            res:{
                                ok:1,
                                data:result
                            }
                        });
                    }else{
                        res.send({
                            res:{
                                ok:0,
                                msg:"获取个人信息失败，请稍后重试！"
                            }
                        })
                    }
                }
            });
            connection.release();
        }
    });
});

// 修改密码的接口
router.post('/reset_password',auth, (req, res) => {
    var Pool = mysql.createPool({
        'host':constant.DB_HOST_NAME,
        'user':constant.DB_USER,
        'password':constant.DB_PWD,
        'database':constant.DB_NAME,
        'multipleStatements': true // 支持执行多条 sql 语句
    });
    Pool.getConnection( (err,connection) => {
        if(err){
            console.log(err);
            res.send({
                'res':{
                    'ok': 0,
                    'msg':'数据库连接失败'
                }
            });
        }else{
            let  sql = "SELECT password FROM user where uid = ?"
            let  sqlParams = [
                req.body.uid
            ];
            connection.query(sql,sqlParams,async (err,data) => {
                if(err){
                    console.log(err);
                    res.statusCode = 500;
                    res.send({
                        'res':{
                            'ok': 0,
                            'msg':'数据库连接失败'
                        }
                    });
                }else{
                    let res_data = JSON.stringify(data);//把data对象转为字符串，去掉RowDataPacket
                    res_data = JSON.parse(res_data);//把results字符串转为json对象
                    if(res_data.length >= 1){
                        const validPassword = await bcrypt.compare(req.body.old_password,res_data[0].password);
                        if(validPassword){
                            // 哈希密码
                            const salt = await bcrypt.genSalt(10);
                            let password = await bcrypt.hash(req.body.new_password,salt);

                            let  sql = "UPDATE user set password = ? where uid = ?;"
                            let  sqlParams = [
                                password,
                                req.body.uid
                            ];
                            connection.query(sql,sqlParams,async(err,data) => {
                                if(err){
                                    console.log(err);
                                    res.statusCode = 500;
                                    res.send({
                                        'res':{
                                            'ok': 0,
                                            'msg':'数据库连接失败'
                                        }
                                    });
                                }else{
                                    let res_data = JSON.stringify(data);//把data对象转为字符串，去掉RowDataPacket
                                    res_data = JSON.parse(res_data);//把results字符串转为json对象
                                    // console.log(res_data);
                                    if(res_data.affectedRows == 1){
                                        res.send({
                                            res:{
                                                ok:1,
                                                msg:'密码修改成功！'
                                            }
                                        });
                                    }else{
                                        res.send({
                                            res:{
                                                ok:0,
                                                msg:"出错了！"
                                            }
                                        })
                                    }
                                }
                            })
                        }else{
                            res.send({
                                res:{
                                    ok:0,
                                    msg:"身份验证失败，旧密码错误！"
                                }
                            })
                        }
                    }else{
                        res.send({
                            res:{
                                ok:0,
                                msg:"出错了！该用户不存在，请确认后重试！"
                            }
                        })
                    }
                }
            });
            connection.release();
        }
    });
});

// 获取个人资产的接口
router.post('/personal_asset',auth, (req, res) => {
    var Pool = mysql.createPool({
        'host':constant.DB_HOST_NAME,
        'user':constant.DB_USER,
        'password':constant.DB_PWD,
        'database':constant.DB_NAME,
        'multipleStatements': true // 支持执行多条 sql 语句
    });
    Pool.getConnection( (err,connection) => {
        if(err){
            console.log(err);
            res.send({
                'res':{
                    'ok': 0,
                    'msg':'数据库连接失败'
                }
            });
        }else{
            // 构造sql语句
            let  sql = "SELECT * FROM files WHERE uploader = ?;"
            let  sqlParams = [
                req.body.uid,
            ];
            connection.query(sql,sqlParams,async (err,data) => {
                if(err){
                    console.log(err);
                    res.statusCode = 500;
                    res.send({
                        'res':{
                            'ok': 0,
                            'msg':'数据库连接失败'
                        }
                    });
                }else{
                    let res_data = JSON.stringify(data);//把data对象转为字符串，去掉RowDataPacket
                    res_data = JSON.parse(res_data);//把results字符串转为json对象
                    // console.log(res_data);
                    if(res_data.length >= 1){
                        let result = [];
                        for(let i in res_data){
                            let temp = {
                                'id':res_data[i].file_id,
                                'name':res_data[i].name,
                                'type':res_data[i].type,
                                'time':res_data[i].time,
                                'score':res_data[i].score
                            }
                            result.push(temp);
                        }
                        res.send({
                            res:{
                                ok:1,
                                data:result
                            }
                        });
                    }else{
                        res.send({
                            res:{
                                ok:0,
                                msg:"您没有上传任何资产！"
                            }
                        })
                    }
                }
            });
            connection.release();
        }
    });
});
// 获取个人消息通知的接口
router.get('/message',auth, (req, res) => {
    var Pool = mysql.createPool({
        'host':constant.DB_HOST_NAME,
        'user':constant.DB_USER,
        'password':constant.DB_PWD,
        'database':constant.DB_NAME,
        'multipleStatements': true // 支持执行多条 sql 语句
    });
    Pool.getConnection( (err,connection) => {
        if(err){
            console.log(err);
            res.send({
                'res':{
                    'ok': 0,
                    'msg':'数据库连接失败'
                }
            });
        }else{
            // 构造sql语句
            let  sql = "SELECT * FROM message WHERE user = ? order by time desc;"
            let  sqlParams = [
                req.query.uid,
            ];
            connection.query(sql,sqlParams,async (err,data) => {
                if(err){
                    console.log(err);
                    res.statusCode = 500;
                    res.send({
                        'res':{
                            'ok': 0,
                            'msg':'数据库连接失败'
                        }
                    });
                }else{
                    let res_data = JSON.stringify(data);//把data对象转为字符串，去掉RowDataPacket
                    res_data = JSON.parse(res_data);//把results字符串转为json对象
                    // console.log(res_data);
                    if(res_data.length >= 1){
                        let result = [];
                        let no_read_count = 0;
                        for(let i in res_data){
                            let isRead = '';
                            if(res_data[i].isRead){
                                isRead = 'read';
                            }else{
                                isRead = 'no read';
                                no_read_count++;
                            }
                            let temp = {
                                'id':res_data[i].message_id,
                                'title':res_data[i].title,
                                'content':res_data[i].content,
                                'time':res_data[i].time,
                                'isRead':isRead
                            }
                            result.push(temp);
                        }
                        res.send({
                            res:{
                                ok:1,
                                data:result,
                                no_read:no_read_count
                            }
                        });
                    }else{
                        res.send({
                            res:{
                                ok:0,
                                msg:"您没有任何新消息！"
                            }
                        })
                    }
                }
            });
            connection.release();
        }
    });
});

// 处理已读消息的接口
router.post('/read',auth, (req, res) => {
    var Pool = mysql.createPool({
        'host':constant.DB_HOST_NAME,
        'user':constant.DB_USER,
        'password':constant.DB_PWD,
        'database':constant.DB_NAME,
        'multipleStatements': true // 支持执行多条 sql 语句
    });
    Pool.getConnection( (err,connection) => {
        if(err){
            console.log(err);
            res.send({
                'res':{
                    'ok': 0,
                    'msg':'数据库连接失败'
                }
            });
        }else{
            // 构造sql语句
            let  sql = "update message set isRead=? WHERE message_id = ?;"
            let  sqlParams = [
                true,
                req.body.message_id,
            ];
            connection.query(sql,sqlParams,async (err,data) => {
                if(err){
                    console.log(err);
                    res.statusCode = 500;
                    res.send({
                        'res':{
                            'ok': 0,
                            'msg':'数据库连接失败'
                        }
                    });
                }else{
                    let res_data = JSON.stringify(data);//把data对象转为字符串，去掉RowDataPacket
                    res_data = JSON.parse(res_data);//把results字符串转为json对象
                    // console.log(res_data);
                    if(res_data.affectedRows == 1){
                        res.send({
                            res:{
                                ok:1,
                                msg:"提交成功！"
                            }
                        });
                    }else{
                        res.send({
                            res:{
                                ok:0,
                                msg:"提交已读消息失败！"
                            }
                        })
                    }
                }
            });
            connection.release();
        }
    });
});
module.exports = router;